package org.example.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.common.utils.DateTimeUtil;
import org.example.db.entity.Role;
import org.example.db.entity.User;
import org.example.db.entity.UserRole;
import org.example.db.mapper.UserRoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserRoleService {

    UserRoleMapper userRoleMapper;

    public UserRoleService(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Transactional
    public int updateUserRole(Long userId, List<Long> roleIdList) {

        int count = roleIdList == null ? 0 : roleIdList.size();

        userRoleMapper.delete(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, userId));
        if(count != 0){
            for(Long roleId: roleIdList){
                String formatTime = DateTimeUtil.getDateTimeString(LocalDateTime.now());
                userRoleMapper.insert(new UserRole(null, userId, roleId, formatTime, formatTime));
            }
        }
        return count;
    }

    @Transactional
    public int addUserRole(Long userId, Long roleId){

        userRoleMapper.delete(new QueryWrapper<UserRole>()
                .lambda().eq(UserRole::getUserId, userId).eq(UserRole::getRoleId, roleId));
        String time = DateTimeUtil.getDateTimeString();
        return userRoleMapper.insert(new UserRole(null, userId, roleId, time, time));
    }

    public List<Role> getRolesByUserId(Long userId){

        return userRoleMapper.getRolesByUserId(userId);
    }

    public void deleteRolesById(Long userId){
        userRoleMapper.delete(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, userId));
    }

    public List<UserRole> getUserRoleByRoleId(Long roleId){

        return userRoleMapper.selectList(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getRoleId, roleId));
    }
}
